<template id="ConfirmProducts">
  <div class="ConfirmProducts" ref="ConfirmProducts">
    <go-to-back />
    <div class="productsContent">
      <p class="productsTitle">
        确认订单 <span>购买数字藏品后，均不支持退换!</span>
      </p>
      <div class="productsBox">
        <table>
          <thead class="tableHeader">
            <tr>
              <td>数字典藏</td>
              <td>订单号</td>
              <td>价格</td>
            </tr>
          </thead>

          <tbody class="tableContent">
            <tr>
              <td>
                <div class="firstClo">
                  <img class="productImg" :src="productInfo.image" />
                  <div class="productInfo">
                    <p class="name">{{ productInfo.goods_name }}</p>
                    <p class="desc">{{ productInfo.goods_desc }}</p>
                  </div>
                </div>
              </td>
              <td>
                <p class="orderSn">{{ order_sn }}</p>
              </td>
              <td>
                <p><span>¥</span>{{ disPrice(productInfo.price) }}</p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="discount-title">
      <span>选择代金券</span>
      <span @click="gotoDiscount">如已获得代金券，请点击此处兑换后即可使用。</span>
    </div>
    <div class="discount">
      <discount-bar v-if="discountData.length > 0" :discountData="discountData"
        @handlePickDiscountCard="handlePickDiscountCard"></discount-bar>

      <div class="discount-none" v-else>
        <p>暂无可用代金券</p>
      </div>
    </div>

    <div class="pay">
      <md-button class="alipay" @click="useAlipay">支付宝支付</md-button>
      <md-button class="otherPay" @click="lianPay">连连支付</md-button>
      <!-- <md-button class="otherPay" @click="cashierPay">首信易支付</md-button> -->

      <!-- <md-button class="otherPay" @click="useWxpay">微信支付</md-button> -->
    </div>

    <el-dialog :visible.sync="dialogVisible" center width="1200px" :close-on-click-modal="false">
      <div class="buyBox">
        <vue-qr :text="baseURL" :callback="qrCallback" :qid="order_sn" :size="350"></vue-qr>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import DiscountBar from "./components/DiscountBar.vue";
import GoToBack from "./components/GoToBack.vue";
import {
  getGoodsInfoApi,
  unifiedOrderApi,
  checkOrderApi,
  UnifiedWxJSApiOrderApi,
  wxPayConfigApi,
  bankcardInfoApi,
  cashierPayApi,
  getAvailableCouponApi,
  payOrderApi,
  unifiedAplipayOrderApi,
  tradeCreateApi
} from "@/api";
import { iscode, getWidth, isWeixin, escapeHTML } from "@/utils";
import { initAPIs } from "@/utils/weixinSDK.js";
import vueQr from "vue-qr";
import { Toast } from "vant";
import baseUrl from "@/utils/baseUrl.js";
import { mapState, mapMutations } from "vuex";
export default {
  name: "ConfirmProducts",
  components: { GoToBack, vueQr, DiscountBar },
  // 定义属性
  data() {
    return {
      phoneNoFabulousIcon: require("@/assets/images/mobile/noFabulousIcon.png"),
      phoneFabulousIcon: require("@/assets/images/mobile/fabulous.png"),
      phoneCollectionIcon: require("@/assets/images/mobile/collection.png"),
      phoneNoCollectionIcon: require("@/assets/images/mobile/noCollectionIcon.png"),
      phoneBackIcon: require("@/assets/images/mobile/phoneBack.png"),
      closeIcon: require("@/assets/images/mobile/closeIcon.png"),
      aliPayIcon: require("@/assets/images/mobile/aliPayIcon.png"),
      wxPayIcon: require("@/assets/images/mobile/wxPayIcon.png"),
      unSelectIcon: require("@/assets/images/mobile/unSelect.png"),
      selectIcon: require("@/assets/images/mobile/select.png"),
      payMode: 1, //0支付宝 1微信
      order_sn: "",
      order_id: "",
      dialogVisible: false,
      productInfo: {},
      baseURL: "",
      platform: 1, //  "platform":1PC 2手机
      currentWidth: "",
      order_price: "", //订单金额
      // 银行卡数量
      card_count: 0,
      // 代金券数据
      discountData: [],
      // 当前选择的代金券索引下标(默认0，代表第一个)
      currentPickIndex: 0,
    };
  },
  computed: {
    ...mapState(["couponId"]),
  },
  // 方法集合
  methods: {
    ...mapMutations(["setCouponId"]),
    // ------ async ------
    // 获取银行卡信息
    async bankcardInfo() {
      let res = await bankcardInfoApi();
      if (iscode(res)) {
        this.card_count = res.result.list.length;
      }
    },
    //连连
    async lianPay() {
      this.setCouponId(this.discountData[this.currentPickIndex]?.id ?? "")
      if (this.card_count > 0) {
        this.$router.push({
          path: "/mail/selectCard",
          query: {
            order_sn: this.order_sn,
          },
        });
      } else {
        this.$router.push({
          path: "/mail/bindCard",
          query: {
            order_sn: this.order_sn,
          },
        });
      }
    },
    // 快捷支付按钮跳转
    async cashierPay() {
      let res = await cashierPayApi({
        order_sn: this.order_sn,
        coupon_id: this.discountData[this.currentPickIndex]?.id ?? "",
      });
      if (iscode(res)) {
        window.location.href = res.result.redirectUrl;
      }
      // if (this.card_count <= 0) {
      //   this.$router.push({
      //     path: "/mail/bindCard",
      //     query: {
      //       order_sn: this.order_sn,
      //     },
      //   });
      // } else {
      //   this.$router.push({
      //     path: "/mail/selectCard",
      //     query: {
      //       order_sn: this.order_sn,
      //     },
      //   });
      // }
    },
    async useWxpay() {
      // let result = await unifiedOrderApi({
      //   order_sn: this.order_sn,
      //   pay_type: 2,
      //   platform: this.platform,
      // });
      // if (iscode(result)) {
      //   this.baseURL = result.result.code_url;
      //   this.dialogVisible = true;
      //   this.checkOrder();
      // }
      this.$router.push({
        path: "wxPay",
        query: {
          id: this.$route.query.id,
          order_sn: this.$route.query.order_sn,
          order_id: this.$route.query.order_id,
        },
      });
    },

    async wxPayConfig() {
      let result = await wxPayConfigApi({
        domain: baseUrl.productionApi,
      });
      if (iscode(result)) {
      }
    },
    // #region 创建订单
    // async createOrder() {
    //   let result = await createOrderApi({
    //     goods_id: this.$route.query.id,
    //     hashcode:
    //       "0x456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5456543fd67hsd3hhjsdb5",
    //     platform: this.platform,
    //   });
    //   if (iscode(result)) {
    //     this.order_sn = result.result.order.order_sn;
    //   }
    // },
    // #endregion
    // 获取商品信息
    async getGoodsInfo() {
      let result = await getGoodsInfoApi({ id: this.$route.query.id });
      if (iscode(result)) {
        this.productInfo = result.result.goods_info;
        this.productInfo.goods_desc = escapeHTML(this.productInfo.goods_desc);
        this.$set(
          this.productInfo,
          "image",
          result.result.show_url + this.productInfo.images[0]
        );
        this.$set(this.productInfo, "isFabulous", result.result.is_likes);
        this.$set(this.productInfo, "fabulous", result.result.goods_likes_cnt);
        this.$set(this.productInfo, "isCollect", result.result.is_collect);
        this.$set(this.productInfo, "collect", result.result.goods_collect_cnt);
        // 支付金额
        this.order_price = result.result.goods_info.price;
      }
    },
    async payOrder() {
      let res = await payOrderApi({ order_sn: this.$route.query.order_sn });
      if (iscode(res)) {
        // console.log(res.result);
        this.productInfo = res.result.order;
        this.productInfo.goods_desc = this.productInfo.goods_desc
          ? escapeHTML(this.productInfo.goods_desc)
          : undefined;
        this.$set(
          this.productInfo,
          "image",
          res.result.show_url + this.productInfo.images[0]
        );
        // 支付金额
        this.order_price = res.result.order.price;
      }
    },
    // 获取代金券信息
    async getAvailableCoupon() {
      let res = await getAvailableCouponApi({
        order_sn: this.$route.query.order_sn,
      });
      if (iscode(res)) {
        // console.log(res.result);
        this.discountData = res.result.list;
      }
    },

    //  ------ pay ------
    qrCallback(url, id) {
      console.log(url, id);
    },
    checkOrder() {
      let that = this;
      let intervalId = setInterval(async () => {
        if (this.dialogVisible == false) {
          clearInterval(intervalId);
        }
        let result = await checkOrderApi({
          order_sn: that.order_sn,
        });
        if (result.code == 0) {
          if (that.platform == 1) {
            that.$message({
              message: result.message,
              iconClass: "mySuccessIcon",
              customClass: "mySuccess",
            });
          } else {
            Toast.success(result.message);
          }
          that.$router.push({
            path: "/payCompleted",
            query: {
              id: that.$route.query.id,
              order_id: that.$route.query.order_id,
            },
          });
          clearInterval(intervalId);
        }
      }, 1000);
    },
    async useAlipay() {
      // let alipayBaseURL = "";
      // if (this.discountData[this.currentPickIndex]?.id ?? "") {
      //   alipayBaseURL =
      //     baseUrl.productionApi +
      //     "/api/pay/unifiedOrder/" +
      //     this.order_sn +
      //     "/" +
      //     this.platform +
      //     "/" +
      //     this.discountData[this.currentPickIndex].id;
      // } else {
      //   alipayBaseURL =
      //     baseUrl.productionApi +
      //     "/api/pay/unifiedOrder/" +
      //     this.order_sn +
      //     "/" +
      //     this.platform;
      // }
      // window.location.href = alipayBaseURL;
      let res = await unifiedAplipayOrderApi({
        order_sn: this.order_sn,
        platform: this.platform,
        coupon_id: this.discountData[this.currentPickIndex]?.id ?? "",
      })
      if (iscode(res)) {
        const divForm = document.getElementsByTagName('alidiv')
        if (divForm.length) {
          document.body.removeChild(divForm[0])
        }
        const div = document.createElement('div')
        div.innerHTML = res.result // data就是接口返回的form 表单字符串
        document.body.appendChild(div)
        // document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
        document.forms[0].submit()
        document.body.removeChild(div)
      }
    },

    //  ------ discount ------
    // 代金券切换：返回切换代金券后的索引下标
    handlePickDiscountCard(currentPickIndex) {
      this.currentPickIndex = currentPickIndex;
    },
    // 代金券折后价
    disPrice(price) {
      let discount = this.discountData[this.currentPickIndex]?.amount ?? 0;
      return parseFloat((price - discount).toFixed(2));
    },

    // ------ goto ------
    gotoDiscount() {
      this.$router.push("/discount");
    },
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.wxPayConfig();
    // 获取商品信息
    // this.getGoodsInfo();
    this.payOrder();
    // 获取屏幕宽度，判断 pc/phone
    this.currentWidth = getWidth();
    if (this.currentWidth <= 768) {
      this.platform = 2;
    } else {
      this.platform = 1;
    }
    // 获取路由参数里的订单信息
    this.order_sn = this.$route.query.order_sn;
    this.order_id = this.$route.query.order_id;
    // 获取银行卡信息
    this.bankcardInfo();
    // 获取代金券列表
    this.getAvailableCoupon();
  },
};
</script>

<style lang="less" scoped>
.ConfirmProducts {
  width: 100%;
  min-height: 700px;

  p {
    margin-bottom: 0;
  }

  .productsContent {
    margin-top: 30px;

    .productsTitle {
      font-size: 18px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;

      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #aaaaaa;
      }
    }

    .productsBox {
      margin-top: 20px;
      background: #1e2020;
      padding: 20px;
      width: 100%;

      table {
        width: 100%;
        border-collapse: collapse;
      }

      .tableHeader {
        border-bottom: 1px solid #333333;

        td {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #aaaaaa;
          padding-bottom: 12px;
        }
      }

      .tableContent {
        font-size: 14px;
        font-weight: 400;
        color: #666666;

        tr {
          td:first-child {
            width: 550px;
          }
        }

        tr {
          td:last-child {
            width: 150px;
          }
        }

        .firstClo {
          padding-top: 15px;
          display: flex;
        }

        img {
          width: 90px;
          height: 90px;
          margin-right: 20px;
        }

        .orderSn {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
        }

        .productInfo {
          width: 300px;

          .name {
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #ffffff;
            line-height: 18px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .desc {
            margin-top: 10px;
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        p {
          font-size: 16px;
          font-family: DINAlternate-Bold, DINAlternate;
          font-weight: bold;
          color: #00ffb0;
        }

        span {
          font-size: 12px;
          margin-right: 3px;
        }
      }
    }
  }

  .discount-title {
    display: flex;
    justify-content: space-between;
    margin-top: 40px;

    span:nth-child(1) {
      font-size: 18px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
    }

    span:nth-child(2) {
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #999999;
      cursor: pointer;
      transition: color 0.3s ease;
    }

    // span:nth-child(2):hover {
    //   color: #00ffb0;
    // }
  }

  .discount {
    width: 100%;
    max-height: 231px;
    margin-top: 20px;
    overflow: auto;
  }

  .discount-none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 70px;
    background-color: #1e2020;
    box-shadow: 0 2px 4px 0 rgb(18, 18, 18);
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 600;
    color: #999999;
  }

  .pay {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20px;

    .alipay {
      margin: 0;
      background: #0b81ef !important;
      width: 180px;
      height: 38px;
      margin-right: 22px;
      border: none;
      border-radius: unset;
      box-shadow: unset;

      .md-ripple {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
      }
    }

    .otherPay {
      margin: 0;
      background: #4caf50 !important;
      width: 180px;
      height: 38px;
      border: none;
      border-radius: unset;
      box-shadow: unset;

      .md-ripple {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
      }
    }

    .quickpay {
      margin: 0;
      background: #e37215 !important;
      width: 180px;
      height: 38px;
      border: none;
      border-radius: unset;
      box-shadow: unset;
      margin-right: 22px;

      .md-ripple {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #ffffff;
      }
    }
  }

  .phone {
    display: none;
  }
}

@media screen and (max-width: 768px) {
  .discount {
    display: none;
  }



  .ConfirmProducts {
    /deep/ .discount-title {
      display: none;
    }

    .productsContent {
      display: none;
    }

    .pay {
      display: none;
    }

    .phone {
      display: block;

      p {
        margin: 0;
      }

      .phoneProduct {
        position: relative;

        .phoneImage {
          width: 100%;
        }

        .phoneMask {
          width: 100%;
          height: 100%;
          background: linear-gradient(360deg,
              #1e2020 0%,
              rgba(0, 0, 0, 0) 100%);
          position: absolute;
          z-index: 9;
          top: 0;
          left: 0;
        }

        .phoneOptions {
          padding: 0 30px;
          position: absolute;
          top: 34px;
          left: 0;
          z-index: 5;
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;

          .phoneback {
            width: 80px;
            height: 80px;
            background: rgba(255, 255, 255, 0.3);
            backdrop-filter: blur(3px);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              width: 40px;
              height: 40px;
            }
          }

          /deep/.van-badge {
            background: #f24038;
            font-size: 24px;
            // border-radius: 50%;
            min-width: 32px;
            min-height: 32px;
            border: none;
            line-height: unset;
            top: 15px !important;
            right: 10px;
          }

          .phoneBadge {

            .phoneFabulous,
            .phoneCollection {
              width: 80px;
              height: 80px;
              background: rgba(255, 255, 255, 0.3);
              backdrop-filter: blur(3px);
              border-radius: 50%;
              position: relative;
              display: flex;
              align-items: center;
              justify-content: center;

              img {
                width: 40px;
                height: 40px;
              }
            }

            .phoneCollection {
              margin-left: 30px;
            }
          }
        }
      }

      .phoneContent {
        margin-top: -150px;
        position: relative;
        z-index: 10;
        background: #1e2020;
        padding: 40px 30px;
        padding-bottom: 378px;

        .closeIcon {
          position: absolute;
          top: 40px;
          right: 40px;
          z-index: 5;
          width: 40px;
          height: 40px;
        }

        .phoneContentInfo {
          .phoneTitle {
            font-size: 40px;
            font-weight: 600;
            color: #ffffff;
            line-height: 40px;
            margin-bottom: 40px;
          }

          .phoneProductInfo {
            display: flex;
            padding-bottom: 40px;
            border-bottom: 1px solid #333;

            .smallImage {
              width: 180px;
              height: 180px;
              margin-right: 30px;
            }

            .phoneInfoRigth {
              max-width: 480px;
              display: flex;
              flex-direction: column;
              justify-content: space-between;

              .phoneProductName {
                font-size: 28px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #ffffff;
                line-height: 36px;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
                margin-bottom: 20px;
              }

              .phoneOrderId {
                color: #999999;
                font-size: 24px;
                font-weight: 400;
                margin-bottom: 20px;
              }

              .phonePrice {
                font-size: 30px;
                font-family: DINAlternate-Bold, DINAlternate;
                font-weight: bold;
                color: #00ffb0;

                span {
                  font-size: 24px;
                  margin-right: 5px;
                }
              }
            }
          }
        }

        .phonePay {
          margin-top: 40px;

          .phonePayTitle {
            font-size: 28px;
            font-weight: 400;
            color: #ffffff;
            font-family: PingFangSC-Regular, PingFang SC;
            margin-bottom: 32px;
          }

          .phonePayMode {
            padding: 44px 30px;
            background: #2b2c2d;
            border-radius: 12px;

            .phoneWxPay {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .phonePayIcon {
                width: 41px;
                height: 41px;
                margin-right: 16px;
              }

              .phonePayType {
                margin-right: auto;
                font-size: 32px;
                font-weight: 600;
                color: #ffffff;
                font-family: PingFangSC-Semibold, PingFang SC;
              }

              .selectIcon {
                width: 40px;
                height: 40px;
              }
            }

            .phoneAliPay {
              margin-bottom: 80px;
            }
          }
        }
      }

      .phoneBottom {
        display: block;
        width: 100%;
        background: rgba(0, 0, 0, 0.8);
        -webkit-backdrop-filter: blur(20px);
        backdrop-filter: blur(20px);
        position: fixed;
        left: 0;
        bottom: 0;
        z-index: 99;

        .bottomContent {
          padding: 26px 30px 66px 30px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .price {
            font-size: 50px;
            font-family: DINAlternate-Bold, DINAlternate;
            font-weight: bold;
            color: #00ffb0;
            display: flex;
            align-items: baseline;
          }

          span {
            font-size: 32px;
            margin-right: 5px;
          }

          .buyButton {
            margin: 0;
            width: 430px;
            height: 72px;
            color: #1e2020 !important;
            background-color: transparent !important;
            background-image: url("../../../../assets/images/mobile/buyBtnBg.png");
            background-size: 100% 100%;
            font-size: 28px;
            font-weight: 600;
            box-shadow: none;

            span {
              font-size: 28px;
            }
          }

          .selloutButton {
            background-image: url("../../../../assets/images/mobile/selloutBtnBg.png");
          }
        }
      }
    }
  }
}
</style>
